/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.cloud.job;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.aizuda.snailjob.client.common.appender.SnailLogbackAppender;
import com.aizuda.snailjob.client.common.event.SnailClientStartingEvent;
import com.aizuda.snailjob.client.starter.EnableSnailJob;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * snail-job配置.
 *
 * @author zengdegui
 * @since 2025/04/17 23:58
 */
@AutoConfiguration
@EnableScheduling
@EnableSnailJob
@Slf4j
public class SnailJobConfiguration {

    /**
     * Logback配置类
     */
    @Configuration
    @ConditionalOnClass(value = {LoggerContext.class, SnailLogbackAppender.class})
    public static class LogbackConfiguration {

        @EventListener(SnailClientStartingEvent.class)
        public void onStarting(SnailClientStartingEvent event) {
            log.info("SnailJob Logback Start");

            LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
            SnailLogbackAppender<ILoggingEvent> appender = new SnailLogbackAppender<>();
            appender.setName("snail_log_appender");
            appender.setContext(context);
            appender.start();
            Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
            rootLogger.addAppender(appender);
        }
    }
}
